<template>
  <div class="col-xs-12 col-md-8 offset-md-2">
    <form class="card comment-form" @submit.prevent="onSubmit">
      <div class="card-block">
        <textarea
          class="form-control"
          placeholder="Write a comment..."
          rows="3"
          v-model="comment.body"
        ></textarea>
      </div>
      <div class="card-footer" >
        <img :src="article.author.image" class="comment-author-img" />
        <button class="btn btn-sm btn-primary">Post Comment</button>
      </div>
    </form>
    <div class="card" v-for="comment in comments" :key='comment.id'>
      <div class="card-block">
        <p class="card-text">{{comment.body}}</p>
      </div>
      <div class="card-footer">
        <nuxt-link :to="{name:'profile',params:{username:comment.author.username}}" class="comment-author">
          <img
            :src="comment.author.image"
            class="comment-author-img"
          />
        </nuxt-link>
        &nbsp;
        <nuxt-link :to="{name:'profile',params:{username:comment.author.username}}" class="comment-author">{{comment.author.username}}</nuxt-link>
        <span class="date-posted">{{comment.areatedAt|date('MMM DD,YYYY')}}</span>
        <span class="mod-options" v-if="article.author.username===user.username">
          <!-- <i class="ion-edit" @click="editComment"></i> -->
          <i class="ion-trash-a" @click="deleteComment($event)" ref="del" :data-id="comment.id"></i>
        </span>
      </div>
    </div>
  </div>
</template>
<script>
import {getComments,addComments,deleteComments} from '@/api/article'

export default {
  name: "ArticleComments",
  props:{
    user:{
      type:Object
    },
    article:{
      type:Object,
      required:true
    }
  },
  data(){
    // console.log(this.user)
    return {
      comments:[],
      comment:{
        body:''
      }
    }
  },
  async mounted(){
    const {data} =await getComments(this.article.slug)
    this.comments=data.comments
  },
  methods:{
    async onSubmit(){
      const {data} = await addComments(this.article.slug,this.comment);
      // console.log(data.comment)
      this.comments.unshift(data.comment)
      this.comment.body=''
    },
    async deleteComment(e){
      const res = await deleteComments(this.article.slug,e.target.getAttribute('data-id'))
      if(res.status===200){
        this.comments.shift()
      }
    },
  }
};
</script>
<style>
</style>